<?php

if ( PRESSLESS_ENV == 'production' )
{
  header("HTTP/1.1 403: Forbidden");
}

require_once('geshi.php');

$language_extension_mappings = array(
  'php' => array('php'),
  'xml' => array('xml', 'xsl')
);

function explode_path($path)
{
  $exploded = array();

  for ($i = 0; $i < strlen($path); $i++)
  {
    if ($path[$i] == '/' or $i == (strlen($path) - 1)) {
      $exploded[] = substr($path, 0, $i+1);
    }
  }

  return $exploded;
}

function xhtml_source_path_links($path)
{
  $xhtml = '';

  $parts = explode_path($path);

  for ($i = 0; $i < count($parts); $i++)
  {
    $target = $parts[$i];
    $name = preg_replace('#^.*/(.+/?)$#', '\\1', $target);
    $xhtml .= "<a href='/pressless/source$target'>$name</a> ";
  }

  return $xhtml;
}

function xhtml_directory_listing($path)
{
  $source_path_url = "/pressless/source$path";
  $xhtml = "<ul>";

  foreach (scandir(PRESSLESS_ROOT_DIR . $path) as $dir_entry)
  {
    if ($dir_entry == '.' or $dir_entry == '..') continue;

    $xhtml .= sprintf('<li><a href="%s">%s</a></li>',  "$source_path_url/$dir_entry",  $dir_entry);
  }

  return $xhtml . "</ul>";
}

function xhtml_code_listing($path)
{
  global $language_extension_mappings;

  $geshi = new GeSHI('', 'php'); // XXX: Is this really necessary?

  $geshi->load_from_file(PRESSLESS_ROOT_DIR . $_GET['source_file'], $language_extension_mappings);
  $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
  $geshi->set_overall_id('line');
  $geshi->enable_ids();

  return $geshi->parse_code();
}

?>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title></title>

    <style type="text/css">
      pre li:target {
        background-color: #ffc;
      }
    </style>
  </head>

  <body>
    <h1><?php echo xhtml_source_path_links($_GET['source_file']) ?></h1>

    <?php
    if ( is_dir(PRESSLESS_ROOT_DIR . $_GET['source_file']) )
      echo xhtml_directory_listing($_GET['source_file']);
    else
      echo xhtml_code_listing($_GET['source_file']);
    ?>
  </body>
</html>
